package com.bjtu.literatureclient.controller.user;

import com.bjtu.literatureclient.api.LoginResultEnum;
import com.bjtu.literatureclient.base.result.Result;
import com.bjtu.literatureclient.domain.team.Team;
import com.bjtu.literatureclient.domain.user.User;
import com.bjtu.literatureclient.domain.user.UserAndTeam;
import com.bjtu.literatureclient.service.team.ITeamService;
import com.bjtu.literatureclient.service.user.IUserService;
import com.bjtu.literatureclient.shiro.UserRealm;
import com.google.gson.Gson;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private ITeamService teamService;
    private Map<String, String> resultMap;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<String> login(HttpServletRequest request, HttpServletResponse response) {
        // username 目前代表 用户号或邮箱号
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Gson gson = new Gson();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // token.setRememberMe(true);
        try {
            if (!subject.isAuthenticated()) {
                //如果没有登录 先登录
                subject.login(token);
            }
            Session session = SecurityUtils.getSubject().getSession();
            User user = (User) session.getAttribute(UserRealm.SESSIOIN_USER_KEY);
            String redirectUrl = userService.loginRedirect(user);
            return Result.success(redirectUrl);
        } catch (LockedAccountException ex) {
            logger.error("用户已被锁定");
            return Result.fail(gson.toJson(LoginResultEnum.LOCKED_ACCOUNT.getMessage()));
        } catch (UnknownAccountException ex) {
            logger.error("账号不存在，或密码错误");
            return Result.fail(gson.toJson(LoginResultEnum.UNKNOWN_ACCOUNT.getMessage()));
        } catch (IncorrectCredentialsException ex) {
            logger.error("账户存在，密码不匹配");
            return Result.fail(gson.toJson(LoginResultEnum.INCORRECT_CREDENTIALS));
        } catch (AuthenticationException ex) {
            logger.error("其他认证异常", ex);
            return Result.fail(gson.toJson(ex.getMessage()));
        } catch (Exception e) {
            logger.error("服务器内部异常", e);
            return Result.fail(gson.toJson(LoginResultEnum.INTERNAL_ERROR));
        }
    }

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request,HttpServletResponse response){
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return "forward:/index.html";
	}


    @RequestMapping(method = RequestMethod.POST, value = "getNewUserNoAndTeamNo") // 获取新用户号和团队号
    public String getNewUserNoAndTeamNo() {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute("userInfo");
        String newUserNo = userService.getNextUserNo(user.getUserTeamNo());

        resultMap = new HashMap<String, String>();
        resultMap.put("code", "200");
        resultMap.put("UserNo", String.format("%08d", Integer.parseInt(newUserNo)));
        resultMap.put("TeamNo", user.getUserTeamNo());
        Gson gson = new Gson();
        return gson.toJson(resultMap);
    }

    // 检查用户邮箱
    @RequestMapping(method = RequestMethod.POST, value = "checkUserEmail")
    public String checkUserEmail(@RequestBody User user) {
        String result = userService.checkUserEmail(user.getUserEmail());
        resultMap = new HashMap<String, String>();
        resultMap.put("data", result);
        Gson gson = new Gson();
        return gson.toJson(resultMap);
    }

    @RequestMapping(method = RequestMethod.POST, value = "changeUserState") // 检查邮箱
    public String changeUserState(@RequestBody User user) {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User u = (User) session.getAttribute("userInfo");

        boolean result = userService.setUserState(u.getUserNo(), user.getUserState());
        resultMap = new HashMap<String, String>();
        if (result) {
            resultMap.put("data", "success");
        } else {
            resultMap.put("data", "fail");
        }

        Gson gson = new Gson();
        return gson.toJson(resultMap);
    }

    @RequestMapping(method = RequestMethod.POST, value = "getSession") // 获取session
    @ResponseBody
    public String getSession() {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute("userInfo");
        Gson gson = new Gson();
        return gson.toJson(user);
    }


    @RequestMapping(method = RequestMethod.POST, value = "getUserAndTeam") // 获取用户所有信息
    @ResponseBody
    public String getUserAndTeam() {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute("userInfo");
        Team team = teamService.selectTeamById(user.getUserTeamNo());
        String role = user.getUserRole();

        int roleIndex = 6;
        try {
            roleIndex = Integer.parseInt(role);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        String roleName = UserRealm.roleList[roleIndex];

        UserAndTeam uat = new UserAndTeam(user.getUserNo(), team.getTeamName(), role, roleName, team.getTeamNo(),
                user.getUserName(), user.getiDNo(), user.getUserPhone(), user.getUserEmail(), user.getNote());

        //resultMap.put("data", uat);
        //resultMap.put("t", team);
        Gson gson = new Gson();
        return gson.toJson(uat);
    }

    //  添加用户
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public String addUser(@RequestBody User user) {
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        SimpleDateFormat createTimeFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat updateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = createTimeFormat.format(date);
        String updateTime = updateTimeFormat.format(date);

        user.setDate(createTime);
        user.setDateTime(updateTime);
        user.setUserState("1");

        int flag = userService.insert(user);
        resultMap = new HashMap<String, String>();
        if (flag == 1) {
            resultMap.put("data", "success");
        } else {
            resultMap.put("data", "error");
        }

        Gson gson = new Gson();
        return gson.toJson(resultMap);
    }

    @RequestMapping(method = RequestMethod.POST, value = "getUsersByTeam") // 获取该团队下所有用户信息
    @ResponseBody
    public String getUsersByTeam() {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute("userInfo");
        String teamNo = user.getUserTeamNo();
        List<UserAndTeam> userteams;
        userteams = userService.getUsersByTeamNo(teamNo);
        Gson gson = new Gson();
        return gson.toJson(userteams);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@RequestBody User user) {
        logger.debug("UserController.update() : "+user);

        resultMap = new HashMap<>();
        if (!StringUtils.isEmpty(user.getUserNo())) {
            long l = System.currentTimeMillis();
            Date date = new Date(l);
            SimpleDateFormat updateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String updateTime = updateTimeFormat.format(date);
            user.setDateTime(updateTime);
            int flag = this.userService.update(user);
            if (flag == 1) {
                resultMap.put("code", "0000");
                resultMap.put("data", "success");
            }
        } else {
            resultMap.put("code", "9999");
            resultMap.put("data", "error");
        }
        Gson gson = new Gson();
        return gson.toJson(resultMap);
    }

    // 获取下一个团队用户号
    @RequestMapping(value = "/getNewUserNo", method = RequestMethod.POST)
    public String getNewUserNo(@RequestParam("teamNo")String teamNo) {
        logger.debug("userController: getNewUserNo :"+ teamNo);

        String userNo = userService.getNewUserNo(teamNo);
        Gson gson = new Gson();
/*        resultMap = new HashMap<>();
        if (userNo.equals("-1")) {
            resultMap.put("code", "-1");
            resultMap.put("data", "获取失败，不能创建新的成员");
        }else{
            resultMap.put("code", "01");
            resultMap.put("data", userNo);
        }*/
        return gson.toJson(userNo);
    }


/*    @RequestMapping(value = "/queryUser/{param}/{value}", method = RequestMethod.GET)
    public String queryUser(@PathVariable("param") String param, @PathVariable("value") String value) {

        logger.debug("param: "+param+" ,value: "+value);
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute("userInfo");
        logger.debug("current user: "+user);

        User user = new User();
        switch (param) {
            case "userTeamNo": {
                user.setUserTeamNo(value);
                break;
            }
            case "userNo": {
                user.setUserNo(value);
                break;
            }
        }
        List<User> userList = this.userService.query(user);
        Team t = new Team();
        t.setTeamNo(userList.get(0).getUserTeamNo());
        System.out.println(t.getTeamNo());
        List<Team> teamList = this.teamService.query(t);
        Gson gson = new Gson();
        switch (param) {
            case "userTeamNo": {
                user.setUserTeamNo(value);
                return gson.toJson(userList);
            }
            case "userNo": {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("user", userList.get(0));
                resultMap.put("team", teamList.get(0));
                return gson.toJson(resultMap);
            }
        }
        int flag = userList.size();

        Map<String, Object> resultMap = new HashMap();
        if (flag > -1) { resultMap.put("code", "0000"); resultMap.put("data", userList); }
        else { resultMap.put("code", "9999"); resultMap.put("data", "error");
        }
        return value;
    }*/

    /*
     * @RequestMapping(value = "/query/{UserNo}/{Password}", method =
     * RequestMethod.GET) public String query(@PathVariable("UserNo") String
     * UserNo, @PathVariable("Password") String Password) { User user = new
     * User(); user.setIfuse("y"); user.setUserNo(UserNo);
     * user.setPassword(Password); List<User> userList =
     * this.userService.query(user); Map<String, Object> resultMap = new
     * HashMap(); if (userList.size() > 0) { resultMap.put("code", "0000");
     * resultMap.put("data", userList.get(0)); } else { resultMap.put("code",
     * "9999"); resultMap.put("data", "error"); } Gson gson = new Gson(); return
     * gson.toJson(resultMap); }
     */
//	@RequestMapping(value = "/query/{UserNo}/{Password}", method = RequestMethod.GET)
//	public String query(@PathVariable("UserNo") String UserNo, @PathVariable("Password") String Password) {
//		User user = new User();
//		user.setIfuse("y");
//		if (ValidatorUtils.isMobile(UserNo)) {
//			user.setUserPhone(UserNo);
//		} else if (ValidatorUtils.isEmail(UserNo)) {
//			user.setUserEmail(UserNo);
//		} else {
//			user.setUserNo(UserNo);
//
//		}
//
//		user.setPassword(Password);
//
//		List<User> userList = this.userService.query(user);
//
//		Map<String, Object> resultMap = new HashMap();
//
//		if (userList.size() > 0) {
//			resultMap.put("code", "0000");
//			resultMap.put("data", userList.get(0));
//		} else {
//
//			resultMap.put("code", "9999");
//			resultMap.put("data", "error");
//		}
//		Gson gson = new Gson();
//		return gson.toJson(resultMap);
//	}

//
//	@RequestMapping(method = RequestMethod.POST)
//	public String add(@RequestBody User user) {
//		user.setIfuse("y");
//		user.setPassword(user.getUserNo());
//		// 通知信息添加至数据库
//		int flag = this.userService.insert(user);
//		Map<String, String> resultMap = new HashMap();
//		if (flag == 1) {
//			resultMap.put("code", "0000");
//			resultMap.put("data", "success");
//		} else {
//			resultMap.put("data", "error");
//			resultMap.put("code", "9999");
//		}
//		Gson gson = new Gson();
//		return gson.toJson(resultMap);
//	}

//	@RequestMapping(method = RequestMethod.POST, value = "insert")
//	public String insert(@RequestBody UserTeam userTeam) {
//
//		User user = new User();
//		user.setIfuse("n");
//		user.setUserNo(userTeam.getUserNo());
//		user.setUserTeamNo(userTeam.getUserTeamNo());
//		user.setUserName(userTeam.getUserName());
//		user.setPassword(userTeam.getPassword());
//		user.setUserPhone(userTeam.getUserPhone());
//		user.setUserEmail(userTeam.getUserEmail());
//		user.setUserRole(userTeam.getUserRole());
//		user.setState(1);
//		Team team = new Team();
//		team.setIfuse("n");
//		team.setTeamNo(userTeam.getTeamNo());
//		team.setTeamName(userTeam.getTeamName());
//		/* team.setTeamEmail(userTeam.getTeamEmail()); */
//		team.setMaxNum(userTeam.getMaxNum());
//		team.setUserName(userTeam.getUserName());
//		team.setUserEmail(userTeam.getUserEmail());
//		team.setUserRole(userTeam.getUserRole());
//		team.setState("B");
//		int flag = this.teamService.insert(team);
//		int flag1 = this.userService.insert(user);
//		Map<String, String> resultMap = new HashMap();
//		if (flag == 1 && flag1 == 1) {
//			resultMap.put("code", "0000");
//			resultMap.put("data", "success");
//		} else {
//			resultMap.put("data", "error");
//			resultMap.put("code", "9999");
//		}
//		Gson gson = new Gson();
//		return gson.toJson(resultMap);
//	}

//	@RequestMapping(method = RequestMethod.POST, value = "addteamuser") // 团队管理员添加成员
////	public String addteamuser(@RequestBody User user) {
////	    user.setUserState("1");
////		user.setIfuse("y");
////		System.out.println("测试  " + user);
////		int flag1 = 1;
////		//int flag1 = this.userService.insert(user);
////		Map<String, String> resultMap = new HashMap();
////		if (flag1 == 1) {
////			resultMap.put("code", "0000");
////			resultMap.put("data", "success");
////		} else {
////			resultMap.put("data", "error");
////			resultMap.put("code", "9999");
////		}
////		Gson gson = new Gson();
////		return gson.toJson(resultMap);
////	}

//	@RequestMapping(method = RequestMethod.POST, value = "modify")
//	public String modify(@RequestBody UserUpdate userUpdate) {
//		User user = new User();
//		/* user.setIfuse("n"); */
//		user.setUserNo(userUpdate.getUserNo());
//		user.setPassword(userUpdate.getPassword());
//		System.out.println(userUpdate.getPassword());
//		int flag1 = this.userService.update(user);
//		Map<String, String> resultMap = new HashMap();
//		Gson gson = new Gson();
//		return gson.toJson(resultMap);
//	}

//	@RequestMapping(method = RequestMethod.POST, value = "update")
//	public String insert(@RequestBody UserUpdate userUpdate) {
//		User user = new User();
//		/* user.setIfuse("n"); */
//		user.setUserNo(userUpdate.getUserNo());
//		user.setUserTeamNo(userUpdate.getUserTeamNo());
//		user.setUserName(userUpdate.getUserName());
//		user.setPassword(userUpdate.getPassword());
//		user.setUserPhone(userUpdate.getUserPhone());
//		user.setUserEmail(userUpdate.getUserEmail());
//		user.setiDNo(userUpdate.getiDNo());
//		user.setNote(userUpdate.getNote());
//		System.out.println(userUpdate.getPassword());
//		user.setState(0);
//		Team team = new Team();
//		team.setTeamNo(userUpdate.getUserTeamNo());
//		if (!userUpdate.getRole().equals("b"))
//			team.setTeamName(userUpdate.getTeamName());
//		team.setUserName(userUpdate.getUserName());
//		team.setUserEmail(userUpdate.getUserEmail());
//		team.setCategory(userUpdate.getCategory());
//		team.setDiscipline(userUpdate.getDiscipline());
//		team.setState("C");
//		System.out.println(userUpdate.getCategory() + "-" + userUpdate.getDiscipline());
//		int flag = this.teamService.update(team);
//		int flag1 = this.userService.update(user);
//		Map<String, String> resultMap = new HashMap();
//		if (flag == 1 && flag1 == 1) {
//			resultMap.put("code", "0000");
//			resultMap.put("data", "success");
//		} else {
//			resultMap.put("data", "error");
//			resultMap.put("code", "9999");
//		}
//		Gson gson = new Gson();
//		return gson.toJson(resultMap);
//	}


}
